package com.iocup.keybastion.core.session;


import com.iocup.keybastion.common.AuthConstant;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xyjxust
 * @create 2022/3/4 15:00
 **/
public class DefaultSessionIdGenerator implements SessionIdGenerator {
    private static final String LOGIN_NAME = "loginName";
    private static final String DEVICE = "device";

    @Override
    public String extractKey(String loginName, String device, String... otherKeys) {
        Map<String, String> values = new LinkedHashMap();
        values.put(LOGIN_NAME,loginName);
        values.put(DEVICE, StringUtils.isBlank(device)? AuthConstant.DEFAULT_DEVICE_NAME: device);
        if(otherKeys!=null&&otherKeys.length>0){
            values.put("otherKeys",String.join(",",otherKeys));
        }
        return generateKey(values);
    }

    protected String generateKey(Map<String, String> values) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] bytes = digest.digest(values.toString().getBytes("UTF-8"));
            return String.format("%032x", new Object[]{new BigInteger(1, bytes)});
        } catch (NoSuchAlgorithmException var4) {
            throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).", var4);
        } catch (UnsupportedEncodingException var5) {
            throw new IllegalStateException("UTF-8 encoding not available.  Fatal (should be in the JDK).", var5);
        }
    }
}
